var express = require('express');
var router = express.Router();
const app= express()
const compression = require('compression');
app.use(compression());
//生成token包(npm i jsonwebtoken)
var jwt = require("jsonwebtoken")

//腾讯人脸识别包(npm i tencentcloud-sdk-nodejs-iai)
const tencentcloud = require("tencentcloud-sdk-nodejs-iai");
let { userModel, listModel, runModel, feedbackModel, phoneModel, statusModel } = require("../model/model")
let multiparty = require("multiparty")
let { randomCode, sendCode } = require('./code')
// ------------登录---------------
//人脸识别
router.get('/test', (req, res) => {
  res.send({
    code: 200,
    msg: 'success'
  })
})
//人脸识别登录
router.post('/faceLogin', async (req, res) => {
  //获取前端传来的base64
  let b64 = req.body.b64

  const IaiClient = tencentcloud.iai.v20200303.Client;

  const clientConfig = {
    credential: {
      //自己的腾讯secretId
      secretId: 'AKIDwocM8ucBobWODwiU7nUCzs94rWNWaf2T',
      //自己的腾讯密匙
      secretKey: 'UsNzcLycAoLi3Oak4RrNzc9mNuJdAqia',
    },
    region: "ap-beijing",  //地域参数（华北地区北京）
    profile: {
      httpProfile: {
        endpoint: "iai.tencentcloudapi.com",
      },
    },
  };

  const client = new IaiClient(clientConfig);

  const params = {
    "GroupIds": [  //你创建的人员库ID
      "zjmshuai99"
    ],
    "Image": b64,  //图片的base64格式编码
    "NeedPersonInfo": 1,  //是否返回人员具体信息。0 为关闭，1 为开启。默认为 0。
    "QualityControl": 0,  //图片质量控制。 0: 不进行控制； 1:较低的质量要求
    "FaceMatchThreshold": 85,  //人脸对比度设置为大于85才可
  };

  let doc = await client.SearchFaces(params)

  //doc为人脸识别后的返回信息
  console.log(doc, 'doc');

  if (doc.Results[0].Candidates.length != 0) {  //表示当前人脸库有该人员
    let personName = doc.Results[0].Candidates[0].PersonName  //拿到该人员的名称
    console.log(personName, 'personNume');

    //生成token
    let token = jwt.sign({ "name": personName }, "face", { expiresIn: '1d' })

    res.send({
      code: 200,
      msg: "登录成功！",
      token
    })

  } else {
    res.send({
      code: 401,
      msg: '人脸库无此人！'
    })
    return false
  }

})


router.get("/getuset_id",async (req,res)=>{
  let _id = req.query.id
  let obj = (await userModel.find({_id}))[0]
  res.send({
    code:"200",
    obj
  })
})

//获取验证码接口
router.get("/code", async (req, res) => {
  let code = randomCode(4);//生成6位数字随机验证码
  sendCode(req.query.iphone, code, function (success) {
    if (success) {
      res.send({
        code: 200,
        msg: "短信验证码发送成功",
        codes: code
      });
    } else {
      res.send("短信验证码发送失败");
    }
  })
})


router.get("/getkm",async (req,res)=>{
  let list = await userModel.find()
  res.send({
    code:200,
    list
  })
})



/* 登录*/
router.post('/login_1', async function (req, res, next) {
  let { iphone, pwd, spwd } = req.body
  let list = await userModel.find({ iphone, pwd, spwd })
  if (list.length > 0) {
    return res.send({
      code: 200,
      msg: "登录成功！",
      list
    })
  } else if (pwd == spwd) {
    if (list.length === 0 && list.length !== '') {
      let lis = await userModel.create({ iphone, pwd, spwd })
      res.send({
        code: 200,
        msg: "注册成功！",
        lis
      })
    } else {
      res.send({
        code: 401,
        msg: "注册失败"
      })
    }
  } else {
    return res.send({
      code: 401,
      msg: "登录失败！"
    })
  }
})

//绑定手机号
router.post('/bind', async function (req, res, next) {
  let { phone, codes } = req.body
  let list = await phoneModel.find({ phone, codes })
  if (list.length > 0) {
    res.send({
      code: 200,
      msg: "绑定成功！",
      list
    })
  } else {
    await phoneModel.create({ phone, codes })
    res.send({
      code: 200,
      msg: '绑定成功'
    })
  }
})

//验证身份
router.post('/status', async function (req, res, next) {
  let { student, name } = req.body
  let list = await statusModel.find({ student, name })
  if (list.length > 0) {
    res.send({
      code: 200,
      msg: "认证成功！",
      list
    })
  } else {
    await statusModel.create({ student, name })
    res.send({
      code: 200,
      msg: '认证成功'
    })
  }
})
// ------------------------------- 

router.post("/putname", async (req, res) => {   //修改名称
  let id = req.body.id
  let name = req.body.name
  await userModel.updateOne({_id:id},{$set:{name:name}})
  res.send({
    code: 200
  })
})


router.post("/puttest", async (req, res) => {   //修改简介
  let id = req.body.id
  let test = req.body.test
  await userModel.updateOne({_id:id},{$set:{test:test}})
  res.send({
    code: 200
  })
})


router.post("/putsex", async (req, res) => {   //修改性别
  let id = req.body.id
  let sex = req.body.sex
  await userModel.updateOne({_id:id},{$set:{sex:sex}})
  res.send({
    code: 200
  })
})


router.post("/putimg", (req, res) => {      //修改头像
  let _id = req.query.id
  let form = new multiparty.Form()
  form.uploadDir = "upload"
  form.parse(req,async (err, fields, files) => {
    await userModel.updateOne({_id},{$set:{img:"http://127.0.0.1:3000/" + files.file[0].path}})
    res.send({
      code: 200,
    })
  })
})

router.post("/addimg", (req, res) => {
  let form = new multiparty.Form()
  form.uploadDir = "upload"
  form.parse(req, (err, fields, files) => {
    res.send({
      code: 200,
      path: "http://127.0.0.1:3000/" + files.file[0].path
    })
  })
})


router.get("/getlist", async (req, res) => {    //获取动态
  let list = await listModel.find()
  res.send({
    code: 200,
    list
  })
})
router.get("/getdanshu", async (req, res) => {    //获取一起跑
  console.log(req.query.name);
  let id = req.query.name
  let list = await listModel.find({ name: id })
  res.send({
    code: 200,
    list
  })
})
router.get("/getdan", async (req, res) => {    //获取动态
  console.log(req.query);

  let id = req.query.id
  let list = await listModel.find({ _id: id })
  res.send({
    code: 200,
    list
  })
})

router.get("/getrun", async (req, res) => {    //获取一起跑
  let list = await runModel.find()
  res.send({
    code: 200,
    list
  })
})
router.get("/getrundan", async (req, res) => {    //获取一起跑
  console.log(req.query);
  let id = req.query.id
  let list = await runModel.find({ _id: id })
  res.send({
    code: 200,
    list
  })
})
router.post("/faping", async (req, res) => {
  let _id = req.query.id
  let data = (await listModel.find({ _id }))[0]
  data.comment.push(req.body)
  await listModel.updateOne({ _id }, { comment: data.comment })
  res.send({
    code: 200
  })
})

router.post("/collect", async (req, res) => {   //是否收藏
  let flag = req.body.flag
  let id = req.body.id
  if (flag) {
    await listModel.updateOne({ _id: id }, { collect: false })
  } else {
    await listModel.updateOne({ _id: id }, { collect: true })
  }
  res.send({
    code: 200
  })
})

router.post("/collectzan", async (req, res) => {   //是否点赞
  let flag = req.body.flag
  let id = req.body.id
  console.log(req.body);

  if (flag) {
    console.log(1);

    await listModel.updateOne({ _id: id }, { praise: false })
  } else {
    console.log(2);
    await listModel.updateOne({ _id: id }, { $set: { praise: true } })
  }
  res.send({
    code: 200
  })
})


module.exports = router;
